Convert Binary to Decimal

Theory:

To convert a binary number to decimal, we multiply each digit of the binary number by 2 raised to the power of its position from the right, starting from 0, and then sum the results.

Python Code:

def binary_to_decimal(binary):
    decimal = 0
    for i in range(len(binary)):
        decimal += int(binary[i]) * 2**(len(binary) - i - 1)
    return decimal

def convert_and_display_decimal():
    binary = input("Enter a binary number: ")
    decimal = binary_to_decimal(binary)
    print("Decimal representation:", decimal)

convert_and_display_decimal()

Example Output 1:

Enter a binary number: 1010

Decimal representation: 10

Example Output 2:

Enter a binary number: 11011

Decimal representation: 27

Code Explanation:

The function binary_to_decimal(binary) converts a binary number to its decimal representation by multiplying each digit by the appropriate power of 2 and summing the results.

The function convert_and_display_decimal() takes input for a binary number, converts it to decimal using the first function, and displays the result.